package com.ruiyian.bridge.info.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.google.common.collect.Maps;
import com.ruiyian.bridge.info.domain.DialyReport;
import com.ruiyian.bridge.info.mapper.DialyReportMapper;
import com.ruiyian.bridge.info.service.*;
import com.ruiyian.bridge.project.domain.BridgeInfo;
import com.ruiyian.bridge.project.domain.DeviceWarnSet;
import com.ruiyian.bridge.project.domain.MeasurePoint;
import com.ruiyian.bridge.project.domain.vo.DataAnalysisDto;
import com.ruiyian.bridge.project.domain.vo.DataAnalysisVo;
import com.ruiyian.bridge.project.enums.DeviceTypeEnum;
import com.ruiyian.bridge.project.enums.WarnDgreeEnum;
import com.ruiyian.bridge.project.service.BridgeInfoService;
import com.ruiyian.bridge.project.service.DeviceWarnSetService;
import com.ruiyian.bridge.project.service.MeasurePointfoService;
import com.ruiyian.common.config.RuoYiConfig;
import com.ruiyian.common.utils.DateUtils;
import com.ruiyian.common.utils.WordUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;


/**
 * @author chong
 * @email 673426164@qq.com
 * @create 2022/6/17
 * Desc: 监测日报
 */
@Service
public class DialyReportServiceImpl extends ServiceImpl<DialyReportMapper,DialyReport> implements DialyReportService {
    @Autowired
    private DialyReportMapper dialyReportMapper;
    private static final String SEPARATOR = "/";
    @Value("${api.profile}")
    private String uploadPath;
    @Autowired
    private MeasurePointfoService measurePointfoService;
    @Autowired
    private BridgeInfoService bridgeInfoService;
    @Autowired
    private DistanceInfoService distanceInfoService;
    @Autowired
    private TemperatureService temperatureService;
    @Autowired
    private VehicleWeightService vehicleWeightService;
    @Autowired
    private VibrationAccelerationService vibrationAccelerationService;
    @Autowired
    private Mmh2oInfoService mmh2oInfoService;
    @Autowired
    private DipmonitorInfoService dipmonitorInfoService;

    @Autowired
    private DeviceWarnSetService deviceWarnSetService;


    /**
     * 列表查询
     * @param dialyReport
     * @return
     */
    @Override
    public List<DialyReport> list(DialyReport dialyReport) {
        return dialyReportMapper.list(dialyReport);
    }


    /**
     * 生成日报
     */
    @Override
    public void creatDoc() {
        List<DialyReport> addList = new ArrayList<>();
        String date = DateUtils.getNextDate(3, new Date(), -1, new SimpleDateFormat("yyyy年MM月dd"));
        String reportDate = DateUtils.getNextDate(3, new Date(), -1, new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"));
        String yesDate = DateUtils.getNextDate(3, new Date(), -1, new SimpleDateFormat("yyyy-MM-dd"));
        String time = DateUtils.getNowDateymd();
        String tempUrl = RuoYiConfig.getTemplatePath()  + "/daily.docx";
        String path = "/report/"+ time;
        String  fileUploadPath = RuoYiConfig.getReportPath() + SEPARATOR +time;
//        String date = DateUtils.getDate("yyyy年MM月dd日");
        File dir = new File(fileUploadPath);
        if (!dir.exists()) {
            dir.mkdirs();
        }
        List<MeasurePoint> ceDianList = measurePointfoService.getMeasPointListAll();
        Map<Long, List<MeasurePoint>> collect = ceDianList.stream().filter(p->null!=p.getBridgeId()).collect(Collectors.groupingBy(MeasurePoint::getBridgeId));
        for (Map.Entry<Long, List<MeasurePoint>> m : collect.entrySet()) {
            DialyReport dialyReport = new DialyReport();
            dialyReport.setCreateTime(new Date());
            dialyReport.setReportTime(DateUtils.date2Str(DateUtils.parseDate(reportDate),new SimpleDateFormat("yyyy-MM-dd HH:mm:ss")));
            String fileName = UUID.randomUUID().toString() + ".docx";
            String fullPath = fileUploadPath + SEPARATOR;
            Map<String, Object> data = Maps.newHashMap();
            BridgeInfo bridgeInfo = bridgeInfoService.selectTBridgeInfoById(m.getKey());
            if(null == bridgeInfo){
                continue;
            }
            data.put("nowDate", date);
            data.put("bridgeName", bridgeInfo.getBridgeName());

            // 系统运行情况
            List<Map<String, Object>> dataList = new ArrayList<>();
            // 数据统计
            List<Map<String, Object>> dataListStatis = new ArrayList<>();
            List<MeasurePoint> value = m.getValue();
            Integer errNum = 0;
            Map<String, List<MeasurePoint>> listMap = value.stream().collect(Collectors.groupingBy(MeasurePoint::getType));
            for (Map.Entry<String, List<MeasurePoint>> d : listMap.entrySet()) {
                // 运行情况
                Map<String, Object> map = Maps.newHashMap();
                DeviceTypeEnum em = DeviceTypeEnum.getEm(Integer.parseInt(d.getKey()));
                map.put("typeName", em.getDesc());
                map.put("total", d.getValue().size());
                List<DataAnalysisVo> dataAnalysisVos = null;
                if(d.getKey().equals(String.valueOf(DeviceTypeEnum.DISTANCE.getType()))){
                    dataAnalysisVos = distanceInfoService.getNowMinDataByType(new DataAnalysisDto(Integer.parseInt(d.getKey()),m.getKey()));
                }else if(d.getKey().equals(String.valueOf(DeviceTypeEnum.MMH2O.getType()))){
                    dataAnalysisVos = mmh2oInfoService.getNowMinDataByType(new DataAnalysisDto(Integer.parseInt(d.getKey()),m.getKey()));
                }else if(d.getKey().equals(String.valueOf(DeviceTypeEnum.DIPMONITOR.getType()))){
                    dataAnalysisVos = dipmonitorInfoService.getNowMinDataByType(new DataAnalysisDto(Integer.parseInt(d.getKey()),m.getKey()));
                }
                map.put("errNum", d.getValue().size()-dataAnalysisVos.size());
                errNum+=d.getValue().size()-dataAnalysisVos.size();
                dataList.add(map);
                // 数据统计
                DataAnalysisVo dataAnalysisVo = null;
                if(d.getKey().equals(String.valueOf(DeviceTypeEnum.DISTANCE.getType()))){
                    dataAnalysisVo = distanceInfoService.queryNowDisByDateType(new DataAnalysisDto(Integer.parseInt(d.getKey()), yesDate));
                }else if(d.getKey().equals(String.valueOf(DeviceTypeEnum.MMH2O.getType()))){
                    dataAnalysisVo = mmh2oInfoService.queryNowDisByDateType(new DataAnalysisDto(Integer.parseInt(d.getKey()),yesDate));
                }else if(d.getKey().equals(String.valueOf(DeviceTypeEnum.DIPMONITOR.getType()))){
                    dataAnalysisVo = dipmonitorInfoService.queryNowDisByDateType(new DataAnalysisDto(Integer.parseInt(d.getKey()),yesDate));
                }
                if(null!=dataAnalysisVo){
                    Map<String, Object> mapStatis = Maps.newHashMap();
                    mapStatis.put("typeName", em.getDesc());
                    mapStatis.put("sensorNo", dataAnalysisVo.getSensorNo());
                    if(d.getKey().equals(String.valueOf(DeviceTypeEnum.DISTANCE.getType()))){
                        mapStatis.put("level", WarnDgreeEnum.getWarnDegreeByDegree(getStatus(dataAnalysisVo.getDistance())).getDesc());
                        mapStatis.put("num",dataAnalysisVo.getDistance());
                    }else if(d.getKey().equals(String.valueOf(DeviceTypeEnum.MMH2O.getType()))){
                        mapStatis.put("level", WarnDgreeEnum.getWarnDegreeByDegree(getStatus(dataAnalysisVo.getJgValue())).getDesc());
                        mapStatis.put("num",dataAnalysisVo.getJgValue());
                    }else if(d.getKey().equals(String.valueOf(DeviceTypeEnum.DIPMONITOR.getType()))){
                        mapStatis.put("level", WarnDgreeEnum.getWarnDegreeByDegree(getStatus(dataAnalysisVo.getYval())).getDesc());
                        mapStatis.put("num","x="+dataAnalysisVo.getXval()+",y="+dataAnalysisVo.getYval()+",z="+dataAnalysisVo.getZval());
                    }
                    dataListStatis.add(mapStatis);
                }
            }
            data.put("errNum", errNum);
            data.put("dataList", dataList);
            data.put("dataListStatis", dataListStatis);
            WordUtil.exportWord(tempUrl, fullPath, fileName, data);
            StringBuffer sb = new StringBuffer();
            sb.append("profile");
            sb.append(path);
            sb.append(SEPARATOR);
            sb.append(fileName);
            dialyReport.setReportName(fileName);
            dialyReport.setReportUrl(sb.toString());
            dialyReport.setReportType("日报告");
            dialyReport.setDelFlag("0");
            dialyReport.setBridgeId(m.getKey());
            addList.add(dialyReport);
        }
        saveBatch(addList);
    }
    public String getStatus(String value){
        List<DeviceWarnSet> setList = deviceWarnSetService.selectTSensorWarnSetList(new DeviceWarnSet());
        Double yellow1 = 0.0;
        Double orange1 = 0.0;
        Double red1 = 0.0;
        for (DeviceWarnSet sensorWarnSet : setList) {
            if(WarnDgreeEnum.YELLOW.getWarnDgree().equals(sensorWarnSet.getWarnDgree())) {
                yellow1 = sensorWarnSet.getDisLimitUpVlue();
            }
            if(WarnDgreeEnum.ORANGE.getWarnDgree().equals(sensorWarnSet.getWarnDgree())) {
                orange1 = sensorWarnSet.getDisLimitUpVlue();
            }
            if(WarnDgreeEnum.RED.getWarnDgree().equals(sensorWarnSet.getWarnDgree())) {
                red1 = sensorWarnSet.getDisLimitUpVlue();
            }
        }
        return checkData(value, yellow1, orange1, red1);
    }
    private String checkData(String record, Double yellow, Double orange, Double red) {
        String rest;
        try {
            double data = Double.valueOf(record);
            //data  = Math.abs(data);
            if(data < yellow) {
                rest = "0";
            }else if (data < orange) {
                rest = "1";
            }else if (data < red) {
                rest = "2";
            }else {
                rest = "3";
            }
        } catch (Exception e) {
            rest = "-1";
        }
        return rest;
    }

    @Override
    public int deleteByIds(Long[] ids) {
       return  this.dialyReportMapper.deleteByIds(ids);
    }
}
